<?php

namespace App\Models\SubAccount;

use App\Models\ShopManager;
use Illuminate\Database\Eloquent\Model;
use App\Models\ShopDetail;
use Illuminate\Database\Eloquent\Casts\Attribute;
use DB;

class SubAccountLoginLogoutRecord extends Model
{

    protected $guarded=[];
    protected $appends=['today_records','yesterday_records','staff_names'];

    //关联子账号
    public function account(){
        return $this->belongsTo(SubAccount::class,'sub_account_id');
    }

    //关联店铺
    public function shop(){
        return $this->belongsTo(ShopDetail::class,'shop_id');
    }
    //子账号绑定的客服名字
    protected function staffNames(): Attribute
    {
        return Attribute::make(
            get: fn ($value,$attributes) => $this->getStaffNames(),
        );
    }
    public function getStaffNames(){
        $names=[];
        if($this->account){
            $names=$this->account->staff()->pluck('name');
        }
        return count($names)?$names->implode('，'):'';
    }

    //关联今天的记录
    protected function todayRecords(): Attribute
    {
        return Attribute::make(
            get: fn ($value,$attributes) => $this->yesterdayLogs($attributes['log_in_out_date'],$attributes['sub_account_id'],'today'),
        );
    }
    //关联昨天的记录
    protected function yesterdayRecords(): Attribute
    {
        return Attribute::make(
            get: fn ($value,$attributes) => $this->yesterdayLogs($attributes['log_in_out_date'],$attributes['sub_account_id'],'yesterday'),
        );
    }
    //某个子账号某天的记录
    public function yesterdayLogs($date,$id,$type='today'){
        if($type=='yesterday'){
            $date=date('Y-m-d',strtotime($date)-24*3600);
        }
        $where=[
            'sub_account_id'=>$id,
            'log_in_out_date'=>$date,
        ];
        //此处不能用模型方式去获取数据，会使模型中的修改器成为递归方法
        return DB::table('sub_account_login_logout_records')->where($where)->select($this->getYesterdayColumns())->get();
    }
    public function getYesterdayColumns(){
        return ['id','sub_account_id','log_in_out_date','record_code','shift_name','on_off_time','login_certificate','exception_img','logout_log','is_data_recorded',];
    }

}
